package com.microframework.base.data.utils;

import okhttp3.FormBody;
import okhttp3.RequestBody;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

public class UrlEncodedFormBuilder {

    /**
     * 构建支持嵌套结构的 application/x-www-form-urlencoded 请求体
     * @param formParams JSON 数据（可能包含嵌套对象或数组）
     * @return RequestBody
     */
    public static RequestBody buildUrlEncodedForm(JSONObject formParams) {
        FormBody.Builder builder = new FormBody.Builder();
        
        if (formParams != null) {
            addJsonToFormBody(builder, formParams, "");
        }
        
        return builder.build();
    }

    /**
     * 递归添加 JSON 数据到 FormBody.Builder
     * @param builder FormBody.Builder
     * @param data 当前层级的 JSON 数据
     * @param parentKey 父级 key（用于嵌套结构，如 "user[name]"）
     */
    private static void addJsonToFormBody(FormBody.Builder builder, Object data, String parentKey) {
        if (data instanceof JSONObject) {
            // 处理嵌套对象
            JSONObject jsonObject = (JSONObject) data;
            for (String key : jsonObject.keySet()) {
                String currentKey = parentKey.isEmpty() ? key : parentKey + "[" + key + "]";
                addJsonToFormBody(builder, jsonObject.get(key), currentKey);
            }
        } else if (data instanceof JSONArray) {
            // 处理数组
            JSONArray jsonArray = (JSONArray) data;
            for (int i = 0; i < jsonArray.size(); i++) {
                String currentKey = parentKey + "[" + i + "]";
                addJsonToFormBody(builder, jsonArray.get(i), currentKey);
            }
        } else if (data != null) {
            // 最终值（String、Number、Boolean 等）
            builder.add(parentKey, data.toString());
        }
    }

    // 使用示例
    public static void main(String[] args) {
        String jsonStr = "{\n" +
                "  \"name\": \"张三\",\n" +
                "  \"age\": 25,\n" +
                "  \"address\": {\n" +
                "    \"city\": \"北京\",\n" +
                "    \"street\": \"朝阳区\"\n" +
                "  },\n" +
                "  \"hobbies\": [\"篮球\", \"音乐\"]\n" +
                "}";

        // 解析 JSON 并构建 FormBody
        JSONObject formParams = JSON.parseObject(jsonStr);
        RequestBody requestBody = buildUrlEncodedForm(formParams);

        System.out.println("application/x-www-form-urlencoded 请求体构建完成！");
    }
}